<template>
  <div class="outbound-order-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>出库管理</h2>
      <div class="header-actions">
        <el-dropdown @command="handleAddTypeSelect">
          <el-button type="primary">
            新增<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="内部领料">内部领料</el-dropdown-item>
              <el-dropdown-item command="委外领料">委外领料</el-dropdown-item>
              <el-dropdown-item command="销售出库">销售出库</el-dropdown-item>
              <el-dropdown-item command="采购退货出库">采购退货出库</el-dropdown-item>
              <el-dropdown-item command="其他出库">其他出库</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="success" @click="exportData">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

         <!-- 搜索条件 -->
     <div class="search-section">
       <el-form :model="searchForm" inline>
         <el-form-item>
           <el-input 
             v-model="searchForm.searchText" 
             placeholder="请搜索" 
             clearable 
             style="width: 300px"
           >
             <template #prefix>
               <el-icon><Search /></el-icon>
             </template>
           </el-input>
         </el-form-item>
         <el-form-item>
           <el-button type="primary" @click="loadData">搜索</el-button>
           <el-button @click="resetSearch">重置</el-button>
         </el-form-item>
       </el-form>
     </div>

         <!-- 统计信息 -->
     <div class="statistics-section" v-if="statistics">
       <el-row :gutter="20">
         <el-col :span="6">
           <el-card shadow="hover">
             <div class="stat-item">
               <div class="stat-number">{{ statistics.totalOrders || 0 }}</div>
               <div class="stat-label">总出库单数</div>
             </div>
           </el-card>
         </el-col>
         <el-col :span="6">
           <el-card shadow="hover">
             <div class="stat-item">
               <div class="stat-number">{{ statistics.pendingOrders || 0 }}</div>
               <div class="stat-label">待处理</div>
             </div>
           </el-card>
         </el-col>
         <el-col :span="6">
           <el-card shadow="hover">
             <div class="stat-item">
               <div class="stat-number">{{ statistics.completedOrders || 0 }}</div>
               <div class="stat-label">已完成</div>
             </div>
           </el-card>
         </el-col>
         <el-col :span="6">
           <el-card shadow="hover">
             <div class="stat-item">
               <div class="stat-number">{{ statistics.totalQuantity || 0 }}</div>
               <div class="stat-label">总出库数量</div>
             </div>
           </el-card>
         </el-col>
       </el-row>
     </div>

         <!-- 数据表格 -->
     <div class="table-section">
       <el-table
         :data="tableData"
         v-loading="loading"
         stripe
         border
         style="width: 100%"
       >
         <el-table-column type="selection" width="55" />
         <el-table-column type="index" label="序号" width="60" />
         <el-table-column prop="outboundOrderNumber" label="出库单号" width="150" />
         <el-table-column prop="outboundSubject" label="出库主题" min-width="200" />
         <el-table-column prop="outboundDate" label="出库日期" width="120" />
         <el-table-column prop="outboundType" label="出库类型" width="120">
           <template #default="{ row }">
             <el-tag :type="getTypeTagType(row.outboundType)">
               {{ row.outboundType }}
             </el-tag>
           </template>
         </el-table-column>
         <el-table-column prop="itemSummary" label="物品概要" min-width="200">
           <template #default="{ row }">
             <el-dropdown v-if="row.itemSummary">
               <span class="item-summary">
                 {{ row.itemSummary }}
                 <el-icon class="el-icon--right"><arrow-down /></el-icon>
               </span>
               <template #dropdown>
                 <el-dropdown-menu>
                   <div class="item-details">
                     <div v-for="item in row.details" :key="item.id">
                       {{ item.itemName }}: {{ item.outboundQuantity }}
                     </div>
                   </div>
                 </el-dropdown-menu>
               </template>
             </el-dropdown>
             <span v-else>-</span>
           </template>
         </el-table-column>
         <el-table-column prop="outboundWarehouse" label="出库仓库" width="150" />
         <el-table-column prop="outboundPersonnel" label="出库人员" width="120" />
         <el-table-column prop="totalQuantity" label="出库数量" width="100" />
         <el-table-column label="操作" width="100" fixed="right">
           <template #default="{ row }">
             <el-button type="primary" size="small" @click="viewDetail(row)">
               查看
             </el-button>
           </template>
         </el-table-column>
       </el-table>

             <!-- 分页 -->
       <div class="pagination-section">
         <el-pagination
           v-model:current-page="pagination.pageIndex"
           v-model:page-size="pagination.pageSize"
           :page-sizes="[5, 10, 20, 50]"
           :total="pagination.total"
           layout="total, sizes, prev, pager, next, jumper"
           @size-change="handleSizeChange"
           @current-change="handleCurrentChange"
         />
       </div>
    </div>

         <!-- 新增/编辑对话框 -->
     <el-dialog
       v-model="showAddDialog"
       :title="isEdit ? '编辑出库单' : `新增${selectedOutboundType}出库单`"
       width="80%"
       :before-close="handleDialogClose"
     >
       <el-form
         ref="formRef"
         :model="formData"
         :rules="formRules"
         label-width="120px"
       >
         <!-- 基本信息 -->
         <el-card class="form-card">
           <template #header>
             <span>基本信息</span>
           </template>
           
           <el-row :gutter="20">
             <el-col :span="12">
               <el-form-item label="出库单号" prop="outboundOrderNumber">
                 <el-input v-model="formData.outboundOrderNumber" placeholder="系统自动生成" disabled />
               </el-form-item>
             </el-col>
             <el-col :span="12">
               <el-form-item label="出库主题" prop="outboundSubject">
                 <el-input v-model="formData.outboundSubject" placeholder="请输入出库主题" />
               </el-form-item>
             </el-col>
           </el-row>

           <el-row :gutter="20">
             <el-col :span="12">
               <el-form-item label="出库类型" prop="outboundType">
                 <el-input v-model="formData.outboundType" disabled />
               </el-form-item>
             </el-col>
             <el-col :span="12">
               <el-form-item label="出库日期" prop="outboundDate">
                 <el-date-picker
                   v-model="formData.outboundDate"
                   type="date"
                   placeholder="请选择出库日期"
                   style="width: 100%"
                   format="YYYY-MM-DD"
                   value-format="YYYY-MM-DD"
                 />
               </el-form-item>
             </el-col>
           </el-row>

           <el-row :gutter="20">
             <el-col :span="12">
               <el-form-item label="出库仓库" prop="warehouseId">
                 <el-select 
                   v-model="formData.warehouseId" 
                   placeholder="请选择出库仓库" 
                   style="width: 100%"
                   :loading="warehouseLoading"
                   filterable
                 >
                   <el-option 
                     v-for="warehouse in warehouseOptions" 
                     :key="warehouse.id" 
                     :label="warehouse.warehouseName" 
                     :value="warehouse.id" 
                   />
                 </el-select>
               </el-form-item>
             </el-col>
             <el-col :span="12">
               <el-form-item label="部门" prop="department">
                 <el-select 
                   v-model="formData.department" 
                   placeholder="请选择部门" 
                   style="width: 100%"
                   :loading="departmentLoading"
                   filterable
                 >
                   <el-option 
                     v-for="dept in departmentOptions" 
                     :key="dept.id" 
                     :label="dept.departmentName" 
                     :value="dept.departmentName" 
                   />
                 </el-select>
               </el-form-item>
             </el-col>
           </el-row>

           <el-row :gutter="20">
             <el-col :span="12">
               <el-form-item label="申请人" prop="applicant">
                 <el-input v-model="formData.applicant" placeholder="请输入申请人" />
               </el-form-item>
             </el-col>
             <el-col :span="12">
               <el-form-item label="出库人员" prop="outboundPersonnel">
                 <el-input v-model="formData.outboundPersonnel" placeholder="请输入出库人员" />
               </el-form-item>
             </el-col>
           </el-row>

           <el-form-item label="备注" prop="remarks">
             <el-input
               v-model="formData.remarks"
               type="textarea"
               :rows="3"
               placeholder="请输入备注"
             />
           </el-form-item>
         </el-card>

         <!-- 根据出库类型显示不同的关联信息 -->
         <el-card class="form-card" v-if="showRelatedInfo">
           <template #header>
             <span>{{ getRelatedInfoTitle() }}</span>
           </template>
           
           <!-- 内部领料 -->
           <div v-if="formData.outboundType === '内部领料'">
             <el-row :gutter="20">
               <el-col :span="12">
                 <el-form-item label="领料部门">
                   <el-select 
                     v-model="formData.relatedDepartment" 
                     placeholder="请选择领料部门" 
                     style="width: 100%"
                     :loading="departmentLoading"
                     filterable
                   >
                     <el-option 
                       v-for="dept in departmentOptions" 
                       :key="dept.id" 
                       :label="dept.departmentName" 
                       :value="dept.departmentName" 
                     />
                   </el-select>
                 </el-form-item>
               </el-col>
               <el-col :span="12">
                 <el-form-item label="领料人员">
                   <el-input v-model="formData.relatedPerson" placeholder="请输入领料人员" />
                 </el-form-item>
               </el-col>
             </el-row>
           </div>

           <!-- 委外领料 -->
           <div v-if="formData.outboundType === '委外领料'">
             <el-row :gutter="20">
               <el-col :span="12">
                 <el-form-item label="委外加工单">
                   <el-select v-model="formData.relatedOrderNumber" placeholder="请选择委外加工单" style="width: 100%">
                     <el-option 
                       v-for="order in outsourcingOrders" 
                       :key="order.id" 
                       :label="order.orderNumber" 
                       :value="order.orderNumber" 
                     />
                   </el-select>
                 </el-form-item>
               </el-col>
               <el-col :span="12">
                 <el-form-item label="委外单位">
                   <el-input v-model="formData.relatedCompany" placeholder="请输入委外单位" />
                 </el-form-item>
               </el-col>
             </el-row>
           </div>

           <!-- 销售出库 -->
           <div v-if="formData.outboundType === '销售出库'">
             <el-row :gutter="20">
               <el-col :span="12">
                 <el-form-item label="销售订单">
                   <el-select v-model="formData.relatedOrderNumber" placeholder="请选择销售订单" style="width: 100%">
                     <el-option 
                       v-for="order in salesOrders" 
                       :key="order.id" 
                       :label="order.orderNumber" 
                       :value="order.orderNumber" 
                     />
                   </el-select>
                 </el-form-item>
               </el-col>
               <el-col :span="12">
                 <el-form-item label="客户名称">
                   <el-input v-model="formData.customerName" placeholder="请输入客户名称" />
                 </el-form-item>
               </el-col>
             </el-row>
           </div>

           <!-- 采购退货出库 -->
           <div v-if="formData.outboundType === '采购退货出库'">
             <el-row :gutter="20">
               <el-col :span="12">
                 <el-form-item label="采购订单">
                   <el-select v-model="formData.relatedOrderNumber" placeholder="请选择采购订单" style="width: 100%">
                     <el-option 
                       v-for="order in purchaseOrders" 
                       :key="order.id" 
                       :label="order.orderNumber" 
                       :value="order.orderNumber" 
                     />
                   </el-select>
                 </el-form-item>
               </el-col>
               <el-col :span="12">
                 <el-form-item label="供应商">
                   <el-input v-model="formData.supplierName" placeholder="请输入供应商" />
                 </el-form-item>
               </el-col>
             </el-row>
           </div>
         </el-card>

        <!-- 出库明细 -->
        <el-form-item label="出库明细">
          <div class="detail-section">
            <div class="detail-header">
              <h4>出库明细</h4>
              <el-button type="primary" size="small" @click="addDetailItem">
                <el-icon><Plus /></el-icon>
                添加明细
              </el-button>
            </div>
            <el-table :data="formData.outboundDetails" border style="width: 100%">
              <el-table-column label="序号" type="index" width="60" />
              <el-table-column prop="itemNumber" label="物品编号" width="120">
                <template #default="{ row, $index }">
                  <el-input v-model="row.itemNumber" placeholder="物品编号" />
                </template>
              </el-table-column>
              <el-table-column prop="itemName" label="物品名称" min-width="150">
                <template #default="{ row, $index }">
                  <el-input v-model="row.itemName" placeholder="物品名称" />
                </template>
              </el-table-column>
              <el-table-column prop="specificationModel" label="规格型号" width="120">
                <template #default="{ row, $index }">
                  <el-input v-model="row.specificationModel" placeholder="规格型号" />
                </template>
              </el-table-column>
              <el-table-column prop="unit" label="单位" width="80">
                <template #default="{ row, $index }">
                  <el-input v-model="row.unit" placeholder="单位" />
                </template>
              </el-table-column>
              <el-table-column prop="outboundQuantity" label="出库数量" width="100">
                <template #default="{ row, $index }">
                  <el-input-number v-model="row.outboundQuantity" :min="0" :precision="2" style="width: 100%" />
                </template>
              </el-table-column>
              <el-table-column prop="unitPrice" label="单价" width="100">
                <template #default="{ row, $index }">
                  <el-input-number v-model="row.unitPrice" :min="0" :precision="2" style="width: 100%" />
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="金额" width="120">
                <template #default="{ row, $index }">
                  <el-input-number v-model="row.amount" :min="0" :precision="2" style="width: 100%" />
                </template>
              </el-table-column>
              <el-table-column prop="batchNumber" label="批次号" width="120">
                <template #default="{ row, $index }">
                  <el-input v-model="row.batchNumber" placeholder="批次号" />
                </template>
              </el-table-column>
              <el-table-column prop="remarks" label="备注" min-width="120">
                <template #default="{ row, $index }">
                  <el-input v-model="row.remarks" placeholder="备注" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ row, $index }">
                  <el-button type="danger" size="small" @click="removeDetailItem($index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <!-- 附件管理 -->
        <!-- <el-form-item label="附件管理">
          <div class="attachment-section">
            <div class="attachment-header">
              <h4>附件列表</h4>
              <el-upload
                ref="uploadRef"
                :action="uploadAction"
                :headers="uploadHeaders"
                :data="uploadData"
                :file-list="formData.attachments"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :on-remove="handleFileRemove"
                :before-upload="beforeUpload"
                :multiple="true"
                :show-file-list="false"
                accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.txt,.zip,.rar"
              >
                <el-button type="primary" size="small">
                  <el-icon><Plus /></el-icon>
                  上传附件
                </el-button>
              </el-upload>
            </div>
            
            <el-table :data="formData.attachments" border style="width: 100%">
              <el-table-column prop="attachmentName" label="附件名称" min-width="200" />
              <el-table-column prop="originalFileName" label="原始文件名" min-width="200" />
              <el-table-column prop="fileSize" label="文件大小" width="100">
                <template #default="{ row }">
                  {{ formatFileSize(row.fileSize) }}
                </template>
              </el-table-column>
              <el-table-column prop="fileType" label="文件类型" width="100" />
              <el-table-column prop="createTime" label="上传时间" width="160" />
              <el-table-column label="操作" width="150">
                <template #default="{ row, $index }">
                  <el-button type="primary" size="small" @click="downloadAttachment(row)">
                    下载
                  </el-button>
                  <el-button type="danger" size="small" @click="removeAttachment($index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item> -->
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="出库单详情"
      width="80%"
    >
      <div v-if="detailData" class="detail-content">
        <!-- 基本信息 -->
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="出库单号">{{ detailData.outboundOrderNumber }}</el-descriptions-item>
            <el-descriptions-item label="出库主题">{{ detailData.outboundSubject }}</el-descriptions-item>
            <el-descriptions-item label="出库类型">
              <el-tag :type="getTypeTagType(detailData.outboundType)">{{ detailData.outboundType }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="出库日期">{{ detailData.outboundDate }}</el-descriptions-item>
            <el-descriptions-item label="出库仓库">{{ detailData.outboundWarehouse }}</el-descriptions-item>
            <el-descriptions-item label="仓库ID">{{ detailData.warehouseId }}</el-descriptions-item>
            <el-descriptions-item label="申请人">{{ detailData.applicant }}</el-descriptions-item>
            <el-descriptions-item label="部门">{{ detailData.department }}</el-descriptions-item>
            <el-descriptions-item label="出库人员">{{ detailData.outboundPersonnel }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusTagType(detailData.status)">{{ detailData.status }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
            <el-descriptions-item label="修改时间">{{ detailData.modifyTime }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="3">{{ detailData.remarks || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 出库明细 -->
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>出库明细 ({{ detailData.details ? detailData.details.length : 0 }}条)</span>
            </div>
          </template>
          <el-table :data="detailData.details" border style="width: 100%">
            <el-table-column prop="itemNumber" label="物品编号" width="120" />
            <el-table-column prop="itemName" label="物品名称" min-width="150" />
            <el-table-column prop="specificationModel" label="规格型号" width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="brand" label="品牌" width="100" />
            <el-table-column prop="outboundQuantity" label="出库数量" width="100" />
            <el-table-column prop="unitPrice" label="单价" width="100" />
            <el-table-column prop="amount" label="金额" width="120" />
            <el-table-column prop="batchNumber" label="批次号" width="120" />
            <el-table-column prop="remarks" label="备注" min-width="120" />
          </el-table>
        </el-card>

                 <!-- 附件信息 -->
         <!-- <el-card class="detail-card" v-if="detailData.attachments && detailData.attachments.length > 0">
           <template #header>
             <div class="card-header">
               <span>附件信息</span>
             </div>
           </template>
           <el-table :data="detailData.attachments" border style="width: 100%">
             <el-table-column prop="attachmentName" label="附件名称" min-width="200" />
             <el-table-column prop="originalFileName" label="原始文件名" min-width="200" />
             <el-table-column prop="fileSize" label="文件大小" width="100">
               <template #default="{ row }">
                 {{ formatFileSize(row.fileSize) }}
               </template>
             </el-table-column>
             <el-table-column prop="fileType" label="文件类型" width="100" />
             <el-table-column prop="createTime" label="上传时间" width="160" />
             <el-table-column label="操作" width="100">
               <template #default="{ row }">
                 <el-button type="primary" size="small" @click="downloadAttachment(row)">
                   下载
                 </el-button>
               </template>
             </el-table-column>
           </el-table>
         </el-card> -->
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ArrowDown, Search, Download } from '@element-plus/icons-vue'
import {
  getOutboundOrders,
  getOutboundOrderById,
  createOutboundOrder,
  updateOutboundOrder,
  deleteOutboundOrder,
  getOutboundOrderStatistics,
  GetAllDepartments,
  getWarehouses
} from '@/Https/server'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const isEdit = ref(false)
const formRef = ref()
const detailData = ref(null)
const selectedOutboundType = ref('')

// 搜索表单
const searchForm = reactive({
  searchText: ''
})

// 选项数据
const warehouseOptions = ref([])
const departmentOptions = ref([])
const warehouseLoading = ref(false)
const departmentLoading = ref(false)

const outsourcingOrders = ref([
  { id: 1, orderNumber: 'WW001' },
  { id: 2, orderNumber: 'WW002' },
  { id: 3, orderNumber: 'WW003' }
])

const salesOrders = ref([
  { id: 1, orderNumber: 'XS001' },
  { id: 2, orderNumber: 'XS002' },
  { id: 3, orderNumber: 'XS003' }
])

const purchaseOrders = ref([
  { id: 1, orderNumber: 'CG001' },
  { id: 2, orderNumber: 'CG002' },
  { id: 3, orderNumber: 'CG003' }
])

// 分页信息
const pagination = reactive({
  pageIndex: 1,
  pageSize: 5,
  total: 0
})

// 表格数据
const tableData = ref([])
const statistics = ref(null)

// 表单数据
const formData = reactive({
  id: null,
  outboundOrderNumber: '',
  outboundSubject: '',
  outboundType: '',
  outboundDate: '',
  outboundWarehouse: '',
  warehouseId: null,
  applicant: '',
  department: '',
  outboundPersonnel: '',
  status: '进行中',
  remarks: '',
  outboundDetails: [],
  // attachments: [], // 附件列表
  // 关联信息字段
  relatedDepartment: '',
  relatedPerson: '',
  relatedOrderNumber: '',
  relatedCompany: '',
  customerName: '',
  supplierName: ''
})

// 附件上传相关数据
// const uploadRef = ref()
// const uploadAction = ref('http://localhost:5145/api/FileUpload/UploadFile') // 后端上传接口地址
// const uploadHeaders = {
//   // 如果需要认证头，在这里添加
// }
// const uploadData = reactive({
//   entityId: '', // 业务实体ID
//   entityType: 'OutboundOrder' // 业务类型
// })

// 表单验证规则
const formRules = {
  outboundOrderNumber: [
    { required: true, message: '请输入出库单号', trigger: 'blur' }
  ],
  outboundSubject: [
    { required: true, message: '请输入出库主题', trigger: 'blur' }
  ],
  outboundType: [
    { required: true, message: '请选择出库类型', trigger: 'change' }
  ],
  outboundDate: [
    { required: true, message: '请选择出库日期', trigger: 'change' }
  ],
  warehouseId: [
    { required: true, message: '请选择出库仓库', trigger: 'change' }
  ],
  applicant: [
    { required: true, message: '请输入申请人', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ]
}

// 获取类型标签样式
const getTypeTagType = (type: string) => {
  const typeMap = {
    '委外': 'warning',
    '采购': 'primary',
    '销售': 'success',
    '其他': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取状态标签样式
const getStatusTagType = (status: string) => {
  const statusMap = {
    '进行中': 'warning',
    '已完成': 'success',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

// 计算属性
const showRelatedInfo = computed(() => {
  return formData.outboundType && formData.outboundType !== '其他出库'
})

// 获取关联信息标题
const getRelatedInfoTitle = () => {
  const titleMap = {
    '内部领料': '领料信息',
    '委外领料': '委外信息',
    '销售出库': '销售信息',
    '采购退货出库': '采购信息'
  }
  return titleMap[formData.outboundType] || '关联信息'
}

// 处理新增类型选择
const handleAddTypeSelect = (type: string) => {
  selectedOutboundType.value = type
  formData.outboundType = type
  // 清空附件列表
  // formData.attachments = []
  // uploadData.entityId = ''
  showAddDialog.value = true
}

// 导出数据
const exportData = () => {
  ElMessage.info('导出功能待实现')
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    const response: any = await getOutboundOrders(params)
    if (response.code === 200) {
      tableData.value = response.data.pageData || []
      pagination.total = response.data.totalCount || 0
    } else {
      ElMessage.error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载统计信息
const loadStatistics = async () => {
  try {
    const response: any = await getOutboundOrderStatistics()
    if (response.code === 200) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('加载统计信息失败:', error)
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    searchText: ''
  })
  pagination.pageIndex = 1
  pagination.pageSize = 5
  loadData()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  loadData()
}

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  loadData()
}

// 查看详情
const viewDetail = async (row: any) => {
  try {
    const response: any = await getOutboundOrderById({ id: row.id })
    if (response.code === 200) {
      detailData.value = response.data
      // 确保details字段存在
      if (!detailData.value.details) {
        detailData.value.details = []
      }
      console.log('详情数据:', detailData.value)
      console.log('出库明细:', detailData.value.details)
      showDetailDialog.value = true
    } else {
      ElMessage.error(response.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 编辑项目
const editItem = async (row: any) => {
  try {
    const response: any = await getOutboundOrderById({ id: row.id })
    if (response.code === 200) {
      Object.assign(formData, response.data)
      formData.outboundDetails = response.data.details || []
      // formData.attachments = response.data.attachments || []
      // uploadData.entityId = response.data.id.toString()
      isEdit.value = true
      showAddDialog.value = true
    } else {
      ElMessage.error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  }
}

// 删除项目
const deleteItem = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个出库单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response: any = await deleteOutboundOrder({ id: row.id })
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadData()
      loadStatistics()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 添加明细项
const addDetailItem = () => {
  formData.outboundDetails.push({
    itemNumber: '',
    itemName: '',
    specificationModel: '',
    unit: '',
    brand: '',
    outboundQuantity: 0,
    unitPrice: 0,
    amount: 0,
    batchNumber: '',
    remarks: ''
  })
}

// 删除明细项
const removeDetailItem = (index: number) => {
  formData.outboundDetails.splice(index, 1)
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const submitData = { ...formData }
    const response: any = isEdit.value 
      ? await updateOutboundOrder(submitData)
      : await createOutboundOrder(submitData)
    
    if (response.code === 200) {
      // 如果是新增，设置entityId用于后续附件上传
      // if (!isEdit.value && response.data && response.data.id) {
      //   uploadData.entityId = response.data.id.toString()
      // }
      
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      showAddDialog.value = false
      loadData()
      loadStatistics()
    } else {
      ElMessage.error(response.message || (isEdit.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 对话框关闭处理
const handleDialogClose = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    id: null,
    outboundOrderNumber: '',
    outboundSubject: '',
    outboundType: '',
    outboundDate: '',
    outboundWarehouse: '',
    warehouseId: null,
    applicant: '',
    department: '',
    outboundPersonnel: '',
    status: '进行中',
    remarks: '',
    outboundDetails: [],
    // attachments: [], // 清空附件列表
    // 关联信息字段
    relatedDepartment: '',
    relatedPerson: '',
    relatedOrderNumber: '',
    relatedCompany: '',
    customerName: '',
    supplierName: ''
  })
  // uploadData.entityId = '' // 清空entityId
  isEdit.value = false
  showAddDialog.value = false
  selectedOutboundType.value = ''
}

// 附件相关方法

// 上传前验证
// const beforeUpload = (file: File) => {
//   const isValidType = [
//     'image/jpeg', 'image/jpg', 'image/png', 'image/gif',
//     'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
//     'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
//     'text/plain', 'application/zip', 'application/x-rar-compressed'
//   ].includes(file.type)
  
//   const isLt10M = file.size / 1024 / 1024 < 10

//   if (!isValidType) {
//     ElMessage.error('只能上传图片、文档、表格、文本、压缩包格式的文件!')
//     return false
//   }
//   if (!isLt10M) {
//     ElMessage.error('文件大小不能超过 10MB!')
//     return false
//   }
//   return true
// }

// 上传成功处理
// const handleUploadSuccess = (response: any, file: any) => {
//   if (response.code === 200) {
//     ElMessage.success('附件上传成功')
//     // 将新上传的附件添加到列表中
//     formData.attachments.push({
//       id: response.data.id,
//       attachmentName: response.data.attachmentName,
//       originalFileName: response.data.originalFileName,
//       fileSize: response.data.fileSize,
//       fileType: response.data.fileType,
//       createTime: response.data.createTime,
//       fileUrl: response.data.fileUrl
//     })
//   } else {
//     ElMessage.error(response.message || '上传失败')
//   }
// }

// 上传失败处理
// const handleUploadError = (error: any) => {
//   console.error('上传失败:', error)
//   ElMessage.error('附件上传失败')
// }

// 移除文件
// const handleFileRemove = (file: any) => {
//   console.log('移除文件:', file)
// }

// 删除附件
// const removeAttachment = async (index: number) => {
//   try {
//     const attachment = formData.attachments[index]
//     await ElMessageBox.confirm('确定要删除这个附件吗？', '提示', {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'warning'
//     })
    
//     const response: any = await DeleteAttachment({ id: attachment.id })
//     if (response.code === 200) {
//       ElMessage.success('删除成功')
//       formData.attachments.splice(index, 1)
//     } else {
//       ElMessage.error(response.message || '删除失败')
//     }
//   } catch (error) {
//     if (error !== 'cancel') {
//       console.error('删除附件失败:', error)
//       ElMessage.error('删除附件失败')
//     }
//   }
// }

// 下载附件
// const downloadAttachment = async (attachment: any) => {
//   try {
//     if (attachment.fileUrl) {
//       // 创建一个临时的a标签来下载文件
//       const link = document.createElement('a')
//       link.href = attachment.fileUrl
//       link.download = attachment.originalFileName || attachment.attachmentName || 'download'
//       link.target = '_blank'
//       document.body.appendChild(link)
//       link.click()
//       document.body.removeChild(link)
//       ElMessage.success('开始下载附件')
//     } else {
//       ElMessage.warning('文件链接不可用')
//     }
//   } catch (error) {
//     console.error('下载附件失败:', error)
//     ElMessage.error('下载附件失败')
//   }
// }

// 获取附件列表
// const fetchAttachments = async (entityId: string) => {
//   try {
//     const response: any = await GetAttachmentsByEntityId({ 
//       entityId: entityId, 
//       entityType: 'OutboundOrder' 
//     })
//     if (response.code === 200) {
//       formData.attachments = response.data || []
//     } else {
//       console.error('获取附件列表失败:', response.message)
//     }
//   } catch (error) {
//     console.error('获取附件列表失败:', error)
//   }
// }

// 格式化文件大小
// const formatFileSize = (bytes: number) => {
//   if (bytes === 0) return '0 B'
//   const k = 1024
//   const sizes = ['B', 'KB', 'MB', 'GB']
//   const i = Math.floor(Math.log(bytes) / Math.log(k))
//   return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
// }

// 获取部门列表
const fetchDepartments = async () => {
  departmentLoading.value = true
  try {
    const response: any = await GetAllDepartments()
    if (response.code === 200) {
      departmentOptions.value = response.data
    } else {
      ElMessage.error(response.message || '获取部门列表失败')
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  } finally {
    departmentLoading.value = false
  }
}

// 获取仓库列表
const fetchWarehouses = async () => {
  warehouseLoading.value = true
  try {
    const response: any = await getWarehouses()
    if (response.code === 200) {
      warehouseOptions.value = response.data
    } else {
      ElMessage.error(response.message || '获取仓库列表失败')
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  } finally {
    warehouseLoading.value = false
  }
}

// 监听仓库ID变化，自动设置仓库名称
watch(() => formData.warehouseId, (newWarehouseId) => {
  if (newWarehouseId) {
    const selectedWarehouse = warehouseOptions.value.find(w => w.id === newWarehouseId)
    if (selectedWarehouse) {
      formData.outboundWarehouse = selectedWarehouse.warehouseName
    }
  } else {
    formData.outboundWarehouse = ''
  }
})

// 页面初始化
onMounted(() => {
  loadData()
  loadStatistics()
  fetchDepartments()
  fetchWarehouses()
})
</script>

<style scoped>
.outbound-order-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.item-summary {
  cursor: pointer;
  color: #409eff;
}

.item-summary:hover {
  text-decoration: underline;
}

.item-details {
  padding: 10px;
  max-height: 200px;
  overflow-y: auto;
}

.form-card {
  margin-bottom: 20px;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.statistics-section {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.table-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  padding: 20px;
  text-align: right;
}

.detail-section {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.detail-header h4 {
  margin: 0;
  color: #303133;
}

.detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  color: #303133;
}

.dialog-footer {
  text-align: right;
}

.attachment-section {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.attachment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.attachment-header h4 {
  margin: 0;
  color: #303133;
}
</style>
